"use client";

import { useState, useEffect } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Textarea } from "@/components/ui/textarea";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Table, TableHeader, TableRow, TableHead, TableBody, TableCell } from "@/components/ui/table";
import { VmsAsr } from "@/types/Model";
import { toast } from "@/hooks/use-toast";
import moment from "moment";


export default function SubtitlePage() {
  const [audioFile, setAudioFile] = useState<File | null>(null);
  const [subtitles, setSubtitles] = useState<VmsAsr[]>([]);
  const [editingSubtitle, setEditingSubtitle] = useState<VmsAsr | null>(null);
  const [isProcessing, setIsProcessing] = useState(false);

  // 获取历史字幕记录
  const fetchSubtitles = async () => {
    try {
      const response = await fetch('/api/subtitle');
      const data = await response.json();
      setSubtitles(Array.isArray(data) ? data : []);
    } catch (error) {
      console.error('Failed to fetch subtitles:', error);
      setSubtitles([]);
      toast({
        variant: "destructive",
        title: "获取字幕记录失败",
        description: "无法获取历史字幕记录，请稍后重试",
      });
    }
  };

  // 刷新任务状态
  const handleRefreshTask = async (id: string) => {
    try {
      const response = await fetch(`/api/subtitle/task/${id}`);
      if (!response.ok) {
        throw new Error('Refresh failed');
      }

      const updatedSubtitle = await response.json();
      setSubtitles(prev => 
        prev.map(sub => 
          sub.id === updatedSubtitle.id ? updatedSubtitle : sub
        )
      );
      toast({
        title: "刷新成功",
        description: `任务状态已更新：${updatedSubtitle.status === "0" ? "处理中" : "成功"}`,
      });
    } catch (error) {
      console.error('Failed to refresh task:', error);
      toast({
        variant: "destructive",
        title: "刷新失败",
        description: "任务状态刷新失败，请稍后重试",
      });
    }
  };

  useEffect(() => {
    fetchSubtitles();
  }, []);

  // 处理文件上传
  const handleFileUpload = async () => {
    if (!audioFile) return;
  
    setIsProcessing(true);
    try {
      // 检查文件类型是否为音频
      if (!audioFile.type.startsWith('audio/')) {
        throw new Error('请上传有效的音频文件');
      }
  
      const formData = new FormData();
      formData.append('file', audioFile);
  
      const response = await fetch('/api/subtitle/task/upload', {
        method: 'POST',
        body: formData,
      });
  
      if (response.status === 413) {
        // 处理存储空间不足错误
        const errorData = await response.json();
        throw new Error(`存储空间不足：已使用 ${errorData.details?.currentUsage}MB / ${errorData.details?.limit}MB，当前套餐：${errorData.details?.planType}`);
      }
  
      if (!response.ok) {
        // 尝试获取详细错误信息
        try {
          const errorData = await response.json();
          throw new Error(errorData.error || 'Upload failed');
        } catch {
          throw new Error('Upload failed');
        }
      }
  
      const newSubtitle = await response.json();
      
      // 确保上传成功后再创建任务
      if (newSubtitle.url && newSubtitle.key) {
        // 调用字幕生成任务接口
        const taskResponse = await fetch('/api/subtitle/task', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            fileUrl: newSubtitle.url,
            filekey: newSubtitle.key
          }),
        });

        if (!taskResponse.ok) {
          throw new Error('Task creation failed');
        }

        const taskData = await taskResponse.json();
        setSubtitles(prev => [taskData, ...prev]);
        
        toast({
          title: "上传成功",
          description: "音频文件已成功上传，字幕生成任务已创建",
        });
      } else {
        throw new Error('Upload response missing required fields');
      }

    } catch (error) {
      console.error('Failed to upload file:', error);
      toast({
        variant: "destructive",
        title: "上传失败",
        description: error instanceof Error ? error.message : "音频文件上传失败，请检查文件格式后重试",
      });
    } finally {
      setIsProcessing(false);
    }
  };

  // 保存编辑的字幕
  const handleSaveSubtitle = async () => {
    if (!editingSubtitle) return;

    try {
      const response = await fetch(`/api/subtitle/${editingSubtitle.id}`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(editingSubtitle),
      });

      if (!response.ok) {
        throw new Error('Save failed');
      }

      const updatedSubtitle = await response.json();
      setSubtitles(prev => 
        prev.map(sub => 
          sub.id === updatedSubtitle.id ? updatedSubtitle : sub
        )
      );
      setEditingSubtitle(null);
      toast({
        title: "保存成功",
        description: "字幕已成功保存",
      });
    } catch (error) {
      console.error('Failed to save subtitle:', error);
      toast({
        variant: "destructive",
        title: "保存失败",
        description: "字幕保存失败，请稍后重试",
      });
    }
  };

  // 下载字幕文件
  const handleDownloadSubtitle = async (subtitle: VmsAsr) => {
    try {
      const srtContent = subtitle.subtitle_text || '';

      const blob = new Blob([srtContent], { type: 'text/srt' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      // 去掉文件名的.mp4后缀和asr-media_前缀
      const filename = subtitle.filekey ? 
        subtitle.filekey.replace(/\.mp3$/, '').replace(/asr-media_/, '') : 
        'subtitle';
      a.download = `${filename}.srt`;
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
      URL.revokeObjectURL(url);
  
    } catch (error) {
      console.error('Failed to download subtitle:', error);
      toast({
        variant: "destructive",
        title: "下载失败",
        description: "字幕文件下载失败，请稍后重试",
      });
    }
  };

  // 删除字幕记录
  const handleDeleteSubtitle = async (id: string) => {
    try {
      // 二次确认
      const confirmDelete = window.confirm("确定要删除这条字幕记录吗？此操作不可恢复。");
      if (!confirmDelete) return;

      const response = await fetch(`/api/subtitle/${id}`, {
        method: 'DELETE',
      });

      if (!response.ok) {
        throw new Error('Delete failed');
      }

      setSubtitles(prev => prev.filter(sub => sub.id !== id));
      toast({
        title: "删除成功",
        description: "字幕记录已成功删除",
      });
    } catch (error) {
      console.error('Failed to delete subtitle:', error);
      toast({
        variant: "destructive",
        title: "删除失败",
        description: "字幕记录删除失败，请稍后重试",
      });
    }
  };

  return (
    <div className="container mx-auto p-4">
      <Card className="mb-8">
        <CardHeader>
          <CardTitle>字幕生成</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex gap-4">
            <Input 
              type="file" 
              accept="audio/mpeg, .mp3" 
              onChange={(e) => setAudioFile(e.target.files?.[0] || null)}
            />
            <Button onClick={handleFileUpload} disabled={!audioFile || isProcessing}>
              {isProcessing ? '处理中...' : '上传并生成字幕'}
            </Button>
            <Button variant="outline" onClick={fetchSubtitles}>
              刷新
            </Button>
          </div>
        </CardContent>
      </Card>

      <Card>
        <CardHeader>
          <CardTitle>字幕历史记录</CardTitle>
        </CardHeader>
        <CardContent>
          <Table>
            <TableHeader>
              <TableRow>
                <TableHead>文件名</TableHead>
                <TableHead>状态</TableHead>
                <TableHead>创建时间</TableHead>
                <TableHead>操作</TableHead>
              </TableRow>
            </TableHeader>
            <TableBody>
              {subtitles?.map((subtitle) => (
                <TableRow key={subtitle.id}>
                  <TableCell>{subtitle.filekey}</TableCell>
                  <TableCell>{subtitle.status === "0" ? "处理中" : subtitle.status === "1" ? "成功" : subtitle.status}</TableCell>
                  <TableCell>
                    {moment(subtitle.create_time).format('YYYY-MM-DD HH:mm:ss')}
                  </TableCell>
                  <TableCell className="flex gap-2">
                    <Button 
                      variant="ghost" 
                      onClick={() => setEditingSubtitle(subtitle)}
                    >
                      编辑
                    </Button>
                    <Button
                      variant="ghost"
                      onClick={() => handleDownloadSubtitle(subtitle)}
                    >
                      下载
                    </Button>
                    <Button
                      variant="ghost"
                      onClick={() => handleRefreshTask(subtitle.id)}
                    >
                      刷新状态
                    </Button>
                    <Button
                      variant="ghost"
                      className="text-red-500 hover:text-red-600"
                      onClick={() => handleDeleteSubtitle(subtitle.id)}
                    >
                      删除
                    </Button>
                  </TableCell>
                </TableRow>
              ))}
            </TableBody>
          </Table>
        </CardContent>
      </Card>

      {editingSubtitle && (
        <div className="fixed inset-0 bg-black/50 flex items-center justify-center p-4">
          <Card className="w-full max-w-2xl">
            <CardHeader>
              <CardTitle>编辑字幕</CardTitle>
            </CardHeader>
            <CardContent>
              <Textarea
                value={editingSubtitle.subtitle_text || ''}
                onChange={(e) => setEditingSubtitle({
                  ...editingSubtitle,
                  subtitle_text: e.target.value
                })}
                className="min-h-[300px] mb-4"
              />
              <div className="flex justify-end gap-2">
                <Button variant="outline" onClick={() => setEditingSubtitle(null)}>
                  取消
                </Button>
                <Button onClick={handleSaveSubtitle}>保存</Button>
              </div>
            </CardContent>
          </Card>
        </div>
      )}
    </div>
  );
}
